<template>
  <van-overlay
    :show="show"
    z-index="99"
    :style="{
      'max-width': '500px',
      left: 'unset',
    }"
  >
    <div class="h-full w-full flex-center relative">
      <div
        class="w-24 h-24 bg-[#f0f0f0] flex-center rounded-50% right-70 top-70 absolute"
        v-if="closeIcon"
      >
        <van-icon name="cross" :size="24" color="#444" class="" />
      </div>
      <Advert v-bind="interstitial" />
    </div>
  </van-overlay>
</template>
<script setup lang="ts">
import { debounce } from "lodash-es";

const show = ref(false);
const closeIcon = ref(false);

const interstitial = useGoogleAd("interstitial");

const timeoutId1 = ref<any>(null);
const timeoutId2 = ref<any>(null);

// 标识用户是否滚动过的sessionStorage key
const prefix = "vue-game-box-";
const key = "has-interstitial";

const onScroll = debounce(() => {
  // 用户滚动
  const hasScroll = sessionStorage.getItem(prefix + key);
  if (!hasScroll && !show.value) {
    sessionStorage.setItem(prefix + key, "1");
    show.value = true;
    window.removeEventListener("scroll", onScroll);
    if (timeoutId1.value) clearTimeout(timeoutId1.value);
    if (timeoutId2.value) clearTimeout(timeoutId2.value);
    // 6秒后显示关闭按钮
    timeoutId1.value = setTimeout(() => {
      closeIcon.value = true;
    }, 6000);
    // 8秒后隐藏
    timeoutId2.value = setTimeout(() => {
      show.value = false;
    }, 8000);
  }
}, 2000);

// onBeforeMount(() => {
//   window.addEventListener("scroll", onScroll);
// });
// onBeforeUnmount(() => {
//   window.removeEventListener("scroll", onScroll);
// });

// 获取随机数500-1000
const randomNum = Math.floor(Math.random() * (1000 - 500 + 1)) + 500;

onMounted(() => {
  setTimeout(() => {
    // const hasInterstitial = sessionStorage.getItem(prefix + key);
    if (!show.value) {
      // sessionStorage.setItem(prefix + key, "1");
      show.value = true;
      if (timeoutId1.value) clearTimeout(timeoutId1.value);
      if (timeoutId2.value) clearTimeout(timeoutId2.value);
      // 6秒后显示关闭按钮
      timeoutId1.value = setTimeout(() => {
        closeIcon.value = true;
      }, 6000);
      // 8秒后隐藏
      timeoutId2.value = setTimeout(() => {
        show.value = false;
      }, 8000);
    }
  }, randomNum);
});
</script>
<style scoped lang="scss"></style>
